<?php
if ($isIncome) {
    $transLabel = "Орлого";
} else {
    $transLabel = "Зарлага";
}
?>
<form class="form-horizontal" method="POST" enctype="multipart/form-data" onsubmit="return isValid()">
    <div class="row-fluid">
        <div class="<?php echo $isIncome ? 'span12' : 'span8' ?>">
            <div class="portlet box grey">
                <div class="portlet-title">
                    <div class="caption"><i class="icon-reorder"></i><?php echo $transLabel ?></div>
                    <div class="tools">
                        <a href="javascript:;" class="collapse"></a>
                    </div>
                </div>
                <div class="portlet-body form">
                    <div class="row-fluid">
                        <div class="span6">
                            <div class="control-group">
                                <label class="control-label" for="trans_date"><?php echo $transLabel ?> огноо:</label>
                                <div class="controls">
                                    <input type="text" name="trans_date" id="trans_date" class="m-wrap input-append date datepicker" data-date-format="yyyy-mm-dd" data-date-viewmode="years" readonly="true" value="<?php echo $transaction['trans_date'] ?>">
                                </div>
                            </div>
                        </div>

                        <div class="span6">
                            <div class="control-group">
                                <label class="control-label" for="trans_type">Хаашаа:</label>
                                <div class="controls">
                                    <select name="trans_type" id="trans_type" class="m-wrap">
                                        <?php foreach ($transactionTypes as $i => $v): ?>
                                            <option value="<?php echo $i ?>" <?php echo $i == $transaction['trans_type'] ? 'selected="selected"' : '' ?>><?php echo $v ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row-fluid">
                        <div class="span6">
                            <div class="control-group">
                                <label class="control-label" for="store">Салбар:</label>
                                <div class="controls">
                                    <select name="store" id="store" class="m-wrap">
                                        <?php foreach ($stores as $i => $v): ?>
                                            <option value="<?php echo $i ?>" <?php echo $i == $transaction['store_id'] ? 'selected="selected"' : '' ?>><?php echo $v ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="span6">
                            <div id="trans_ent_div" class="control-group hidden">
                                <label class="control-label" for="trans_ent_id"></label>
                                <div class="controls">
                                    <select name="trans_ent_id" id="trans_ent_id" class="m-wrap">
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row-fluid">
                        <div class="span6">
                            <div class="control-group">
                                <label class="control-label" for="user">Ажилтан:</label>
                                <div class="controls">
                                    <input type="text" id="user" disabled="disabled" value="<?php echo $user['username'] ?>"/>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-actions">
                        <button type="submit" class="btn green"><i class="icon-plus"></i> Хадгалах</button>
                    </div>
                </div>
            </div>
        </div>
        <?php if (!$isIncome): ?>
            <div class="span4">
                <div class="portlet box grey">
                    <div class="portlet-title">
                        <div class="caption"><i class="icon-reorder"></i><?php echo $transLabel ?></div>
                        <div class="tools">
                            <a href="javascript:;" class="collapse"></a>
                        </div>
                    </div>
                    <div class="portlet-body form">
                        <div class="row-fluid">
                            <div class="span12">
                                <div class="control-group">
                                    <label class="control-label" for="trans_total">Нийт:</label>
                                    <div class="controls">
                                        <input type="text" id="trans_total" disabled="disabled" value="<?php echo $transaction['total_price'] ?>"/>
                                        <span class="btn blue" onclick="$('#payment_1').val($('#trans_total').val());
                                                $('#payment_2').val('0')"><i class="icon-arrow-down"></i></span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <?php foreach ($paymentTypes as $id => $ptName): ?>
                            <div class="row-fluid">
                                <div class="span12">
                                    <div class="control-group">
                                        <label class="control-label" for="payment_<?php echo $id ?>"><?php echo $ptName ?>:</label>
                                        <div class="controls">
                                            <input type="number" name="payments[<?php echo $id ?>]" id="payment_<?php echo $id ?>" class="payment" value="<?php echo isset($transactionPayments[$id]) ? $transactionPayments[$id] : 0; ?>"/>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <div class="row-fluid">
        <div class="span12">
            <div class="portlet box blue">
                <div class="portlet-title">
                    <div class="caption"><i class="icon-reorder"></i>Бараанууд</div>
                    <div class="tools">
                        <a href="javascript:;" class="collapse"></a>
                    </div>
                </div>
                <div class="portlet-body form">
                    <table id="transaction_items" class="table table-striped table-bordered table-hover" cellspacing="0" width="100%">
                        <thead>
                            <tr>
                                <th width="70px"></th>
                                <th>#</th>
                                <th>Ангилал</th>
                                <th>Бараа</th>
                                <th>Үнэ</th>
                                <th width="50px">Тоо(ш)</th>
                                <th>Нийт үнэ</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $i = 0; ?>
                            <?php $total = 0; ?>
                            <?php $totalPrice = 0; ?>
                            <?php foreach ($transactionItems as $item): ?>
                                <tr>
                                    <td>
                                        <a class="btn mini red" onclick="removeProduct(this);" href="javascript:;"><i class="icon-trash"> Устгах</i></a>
                                    </td>
                                    <td><?php echo ++$i; ?></td>
                                    <td><?php echo $item['category_name'] ?></td>
                                    <td><?php echo $item['product_name'] ?></td>
                                    <td>
                                        <input class="pprice" type="number" value="<?php echo $item['product_price'] ?>"/>
                                    </td>
                                    <td>
                                        <input type="hidden" value="<?php echo $item['id']; ?>" name="products[<?php echo $i ?>][id]"/>
                                        <input type="hidden" value="<?php echo $item['product_id']; ?>" name="products[<?php echo $i ?>][pid]"/>
                                        <input class="pqty" type="number" value="<?php echo $isIncome ? $item['quantity'] : $item['quantity'] * -1; ?>" name="products[<?php echo $i ?>][qty]"/>
                                    </td>
                                    <td>
                                        <input class="ptprice" type="number" value="<?php echo $item['price'] ?>" name="products[<?php echo $i ?>][price]" readonly="readonly"/>
                                    </td>
                                    <?php $total += ($isIncome ? $item['quantity'] : $item['quantity'] * -1); ?>
                                    <?php $totalPrice += $item['price']; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="5"></td>
                                <td><span id="total_qty"><?php echo $total; ?></span></td>
                                <td><span id="total_price"><?php echo $totalPrice; ?></span></td>
                            </tr>
                            <tr>
                                <td colspan="6"></td>
                                <td id="td_add_product">
                                    <div>
                                        <label for="category" class="">Ангилал:</label>
                                        <select id="category" class="m-wrap">
                                            <option value="0">[Сонгох]</option>
                                            <?php foreach ($categories as $i => $v): ?>
                                                <option value="<?php echo $i ?>"><?php echo $v ?></option>
                                            <?php endforeach; ?>
                                        </select>

                                        <label for="product" class="">Бараа:</label>
                                        <select id="product" class="m-wrap"></select>

                                        <label for="quantity" class="">Тоо(ш):</label>
                                        <input type="number" id="quantity" class="m-wrap">

                                        <br/>
                                        <br/>
                                        <a class="btn mini green" href="javascript:;" onclick="addProduct()"><i class="icon-plus"></i> Нэмэх</a>
                                    </div>
                                </td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</form>

<script type="text/javascript">
    var productTable;
    function categoryChanged() {
        c = $(this).val();
        if (c > 0) {
            $.ajax({
                url: '<?php echo $urlProduct ?>?category_id=' + c + '&with_price=1',
                dataType: 'json',
                success: function(v) {
                    if ($.isEmptyObject(v)) {
                        $('#product').html('<option value="0">[Ангилалд бараа алга]</option>');
                    } else {
                        $('#product').html('');
                        $.each(v, function(i, v) {
                            $('#product').append('<option value="' + i + '" p="' + v.price + '">' + v.name + '</option>');
                        });
                    }
                }
            });
        } else {
            $('#product').html('<option value="0">[Ангилал сонгоно уу]</option>');
        }
    }

    function transTypeChanged() {
        c = $(this).val();
        if (c > 0) {
            var ajaxUrl = '';
            var labelName = '';
            if (c == <?php echo TransactionTable::TRANS_TYPE_CUSTOMER ?>) {
                labelName = 'Үйлчлүүлэгч';
                ajaxUrl = '<?php echo $urlCustomer ?>';
            }
            else if (c == <?php echo TransactionTable::TRANS_TYPE_MOTION ?>) {
                labelName = 'Зөвлөх';
                ajaxUrl = '<?php echo $urlUser . '?type=' . UserTable::TYPE_SALES ?>';
            }
            else if (c == <?php echo TransactionTable::TRANS_TYPE_SUPPLIER ?>) {
                labelName = 'Үйлдвэрлэгч';
                ajaxUrl = '<?php echo $urlManufacturer ?>';
            }
            else if (c == <?php echo TransactionTable::TRANS_TYPE_SERVICE ?>) {
                labelName = 'Гоо сайханч';
                ajaxUrl = '<?php echo $urlUser . '?type=' . UserTable::TYPE_SERVICE ?>';
            }

            if (ajaxUrl != '') {
                $.ajax({
                    url: ajaxUrl,
                    success: function(d) {
                        values = $.parseJSON(d);
                        if ($.isEmptyObject(values)) {
                            $('#trans_ent_div').addClass('hidden');
                            $('#trans_ent_div label').html('');
                            $('#trans_ent_id').html('<option value="0">NONE</option>');
                        } else {
                            $('#trans_ent_div label').html(labelName);
                            if (c == <?php echo TransactionTable::TRANS_TYPE_CUSTOMER ?>) {
                                $('#trans_ent_id').html('<option value="0">Бусад</option>');
                            } else {
                                $('#trans_ent_id').html('<option value="0">[Сонгох]</option>');
                            }
                            $.each(values, function(i, v) {
                                if (i == <?php echo $transaction['trans_entity_id'] ?>) {
                                    $('#trans_ent_id').append('<option value="' + i + '" selected="selected">' + v + '</option>');
                                } else {
                                    $('#trans_ent_id').append('<option value="' + i + '">' + v + '</option>');
                                }
                            });
                            $('#trans_ent_div').removeClass('hidden');
                        }
                    }
                });
            }
        } else {
            $('#trans_ent_div').addClass('hidden');
            $('#trans_ent_div label').html('');
            $('#trans_ent_id').html('<option value="0">NONE</option>');
        }
    }

    function calc() {
        total = 0;
        totalQty = 0;
        $.each(productTable.rows()[0], function(i, v) {
            node = productTable.row(v).node();
            price = $(node).find('.pprice').val();
            qty = $(node).find('.pqty').val();
            $(node).find('.ptprice').val(price * qty);
            total += (price * qty);
            totalQty += (qty * 1);
        });
        $('#total_price').html(total);
        $('#trans_total').val(total);
        $('#total_qty').html(totalQty);
    }

    function addProduct() {
        cat = $('#category').val();
        prod = $('#product').val();
        pp = $('#product option:selected').attr('p');
        qty = $('#quantity').val();
        if (!cat || !prod || !qty) {
            alert('Нэмэх ангилал, бараа ба тоог оруулна уу');
            highlight($('#td_add_product'));
        } else {
            i = productTable.rows()[0].length + 1;
            productTable.row.add(['<a class="btn mini red" onclick="removeProduct(this);" href="javascript:;"><i class="icon-trash"> Устгах</i></a>',
                i,
                $('#category option:selected').html(),
                $('#product option:selected').html(),
                '<input class="pprice" type="number" value="' + pp + '"/>',
                '<input type="hidden" value="' + prod + '" name="products[' + -i + '][pid]"/>' +
                        '<input class="pqty" type="number" value="' + qty + '" name="products[' + -i + '][qty]"/>',
                '<input class="ptprice" type="number" value="' + (qty * pp) + '" name="products[' + -i + '][price]" readonly="readonly"/>']).draw();
            calc();
            $('.pprice, .pqty').keyup(calc);
            $('.pprice, .pqty').change(calc);
        }
    }

    function removeProduct(ele) {
        if (confirm('Та устгахдаа итгэлтэй байна уу?')) {
            productTable.row($(ele).parents('tr')).remove().draw();
        }
    }

    function isValid() {
        if (confirm('Хадгалах уу?')) {
            var sum = 0;
            $('.payment').each(function()
            {
                var value = Number($(this).val());
                if (!isNaN(value))
                    sum += value;
            });
            if ($('#trans_total').val() != sum) {
                alert('Бэлэн ба Картаар төлсөн дүн нийт дүнтэй тэнцэхгүй байна.');
                highlight($('.payment'));
                return false;
            }
            if (productTable.rows()[0].length < 1) {
                alert('Бараагүй <?php echo $transLabel ?> байж болохгүй');
                highlight($('#td_add_product'));
                return false;
            }
            $.each($('.pqty'), function(i, v) {
                if (isNaN(v.value)) {
                    scrollToElement(v);
                    alert('Тоо биш байна');
                    highlight($(v));
                    return false;
                }
                val = parseInt(v.value);
                if (val < 1) {
                    scrollToElement(v);
                    alert('0 ширхэг бараа байж болохгүй');
                    highlight($(v));
                    return false;
                }
            });
            return true;
        }
        return false;
    }

    $(function() {
        productTable = $('#transaction_items').DataTable({
            'paging': false,
            "language": {
                "emptyTable": "Хүснэгт хоосон байна.",
                "info": "_START_-с _END_ хүртэл, Нийт: _TOTAL_",
                "infoEmpty": "Нийт: 0",
                "infoFiltered": "(_MAX_ бичлэгээс хайсан)",
                "infoPostFix": "",
                "infoThousands": ",",
                "lengthMenu": "_MENU_ мөр харах",
                "loadingRecords": "Уншиж байна...",
                "processing": "Тооцоолж байна...",
                "search": "Хайлт:",
                "zeroRecords": "Хайлтын үр дүн олдсонгүй",
                "paginate": {
                    "first": "Эхнийх",
                    "last": "Сүүлийнх",
                    "next": "Дараагийнх",
                    "previous": "Өмнөх"
                },
                "aria": {
                    "sortAscending": ": Өсөхөөр эрэмблэх",
                    "sortDescending": ": Буурахаар эрэмблэх"
                }
            }
        });

        $('.pprice, .pqty').keyup(calc);
        $('.pprice, .pqty').change(calc);

        $('#category').change(categoryChanged);
        $('#category').change();
        $('#trans_type').change(transTypeChanged);
        $('#trans_type').change();

        $(document).on('focus', ':input', function() {
            $(this).attr('autocomplete', 'off');
        });
    });
</script>